﻿function insert(message, user, request) {
    
    delete message.Color;
    delete message.SenderName;
    delete message.CurrentTime;
    
    message.CreatedAt = new Date();
 
    var devicesTable = tables.getTable('Devices');
    devicesTable
        .where({ id: message.DeviceId })
        .read({
            success: function (devices) {
                if (devices.length > 0) {
                    var senderDevice = devices[0];
                    request.execute({
                        success: function() {
                            request.respond();
                            sendPushNotifications(message, senderDevice);
                        }
                    });                    
                }
            }
        })
}


function sendPushNotifications(message, senderDevice) {

    var sql = "SELECT * from skiing.Devices " + 
        "WHERE GroupName = ? AND Id <> ?"
    mssql.query(sql, [message.GroupName, message.DeviceId], {
        success: function(devices) {
            devices.forEach(function(device) {
                
                if (device.Platform == "WP8")
                {                 
                    sendPushNotificationsToWP8(device, message, senderDevice);
                }
                
                //if (device.Platform == "Win8") {}
                //if (device.Platform == "iOS") {}
                
            });
        }
    });
}
  

function sendPushNotificationsToWP8(device, message, senderDevice) {
    push.mpns.sendFlipTile(device.ChannelUri, {
        title: senderDevice.Name,
        backTitle: senderDevice.Name,
        wideBackTitle: "Nachricht von " + senderDevice.Name,
        backContent: message.Text,
        wideBackContent: message.Text,
        }, {
        success: function(pushResponse) {
            console.log("Sent Tile push:", pushResponse);
        }
    });
    
    push.mpns.sendToast(device.ChannelUri, {
        text1: senderDevice.Name + ":",
        text2: message.Text,
        param: "/View/ConversationPage.xaml",
    }, {
        success: function(pushResponse) {
            console.log("Sent Toast push:", pushResponse);
        }
    });    
}
